package com.modules.upms.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.bean.config.YmlConfig;
import com.common.util.R;
import com.common.web.BaseController;
import com.modules.upms.common.util.SysFileUtils;
import com.modules.upms.entity.SysAttachmentInfo;
import com.modules.upms.service.SysAttachmentInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;

/**
 * <p>
 * 系统附件表 前端控制器
 * </p>
 *
 * @author xmh
 * @since 2018-12-22
 */
@Api(tags = {"SysAttachmentInfo" }, description = "系统附件表相关接口")
@RestController
@RequestMapping(value = "/sys/file")
public class SysAttachmentInfoController extends BaseController {

    /**
     * 系统附件表服务类
     */
    @Autowired
    private SysAttachmentInfoService sysAttachmentInfoService;

    /**
     * 属性文件读取
     */
    @Autowired
    private YmlConfig ymlConfig;

    /**
     * 返回系统附件表列表
     *
     * @return 系统附件表列表
     */
    @ApiOperation(value = "返回系统附件表列表", response = SysAttachmentInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "第几页", required = true, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页行数", required = true, dataType = "int", paramType = "query", defaultValue = "20"),
            @ApiImplicitParam(name = "bizId", value = "业务ID", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "bizType", value = "业务类型", required = false, dataType = "string", paramType = "query")
    })
    @GetMapping(value = "/listPage")
    public R<IPage<SysAttachmentInfo>> listPage(@ModelAttribute Page page, @ModelAttribute SysAttachmentInfo query){
        return R.success(sysAttachmentInfoService.getPage(page, query));
    }

    /**
     * 保存系统附件表
     *
     * @param sysAttachmentInfo 实体
     * @return success/false
     */
    @ApiOperation(value = "保存系统附件")
    @PostMapping(value = "/save")
    public R<Boolean> save(@RequestBody SysAttachmentInfo sysAttachmentInfo){
        return R.success(sysAttachmentInfoService.saveOrUpdate(sysAttachmentInfo));
    }

    /**
     * 删除系统附件表
     *
     * @param id ID
     * @return success/false
     */
    @ApiOperation(value = "根据ID删除系统附件")
    @DeleteMapping(value = "/{id}")
    public R<Boolean> delete(@PathVariable Long id){
        return R.success(sysAttachmentInfoService.deleteById(id));
    }

    /**
     * 单个文件上传到本地服务器
     *
     * @return
     */
    @PostMapping(value = "/upload")
    public R<SysAttachmentInfo> fileUpload(HttpServletRequest request) {
        //获取上传request对象
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        //获取上传文件对象
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        //读取配置的根目录
        String fileRootPath = (String) ymlConfig.getMap("upload", String.class).get("file-root-path");
        //业务类型
        String bizType = params.getParameter("bizType");
        return SysFileUtils.upload(fileRootPath, bizType, file);
    }

    /**
     * 文件下载
     * @param response
     * @param fileName
     * @param filePath
     */
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, String fileName, String filePath, String source) {
        //读取配置的根目录
        String fileRootPath = (String) ymlConfig.getMap("upload", String.class).get("file-root-path");
        if(StrUtil.isNotBlank(source) && StrUtil.equals(source, "resources")) {
            fileRootPath = ClassUtil.getClassPath();
        }
        File file = FileUtil.file((fileRootPath + filePath.replace("/files/", "")));
        if (file.exists()) {
            try {
                fileName = new String(fileName.getBytes(), "UTF-8");
                response.setContentType("application/force-download;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; fileName="+  fileName +";filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8"));
                FileUtil.writeToStream(file, response.getOutputStream());
            } catch (Exception e) {
                logger.error("下载文件[" + fileName + "]-下载失败：" + e.getMessage(), e);
            }
        }
    }

    /**
     * 文件是否存在
     * @param filePath
     */
    @GetMapping(value = "/validate")
    public R validate(String filePath, String source) {
        //读取配置的根目录
        String fileRootPath = (String) ymlConfig.getMap("upload", String.class).get("file-root-path");
        if(StrUtil.isNotBlank(source) && StrUtil.equals(source, "resources")) {
            fileRootPath = ClassUtil.getClassPath();
        }
        File file = FileUtil.file((fileRootPath + filePath.replace("/files/", "")));
        if (!file.exists()) {
            return R.error("文件不存在");
        }
        return R.success();
    }

}
